<template>
  <div class="page-common-layout custom-knowledgeBase-container">
    <div class="result-body-warp">
      <!-- 科技成果管理 -->
      <div class="drawing-container">
        <div class="header">
          {{ menuName }}
          <!-- <icon-font
            class="add-file-button"
            type="icon-xinjianwenjianjia"
            @click="handleAAA()"
          ></icon-font> -->
        </div>
        <div class="condition">
          <a-input placeholder="请输入关键字" v-model="keyWord" />
          <div class="search-btn">
            <a-icon type="search" @click="handleFilterTree()" />
          </div>
        </div>
        <div class="tree-container">
          <a-spin :spinning="spinning">
            <a-empty v-if="treeData.length == 0" :description="false" />
            <a-tree
              v-else
              v-model="checkedKeys"
              show-icon
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childList',
                title: 'name',
                key: 'code',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <!-- 自定义图标 -->
              <template slot="custom">
                <icon-font type="icon-wenjianjia-" />
              </template>
              <template slot="title" slot-scope="{ name, total }">
                <div class="custom-tree-title-warp">
                  <div class="title" :title="name">
                    <div>{{ name }}</div>
                    <div class="num">{{ total }}</div>
                  </div>
                </div>
              </template>
            </a-tree>
          </a-spin>
        </div>
      </div>
      <!-- 列表 -->
      <div class="right-container">
        <div class="header">
          <a-button
            type="primary"
            icon="plus"
            :disabled="!currentTreeNode.code"
            @click="handleAdd({}, 1)"
            v-action:kjcggl_add
          >
            新增
          </a-button>
          <div class="search-condition-warp">
            <div class="condition-warp">
              <a-input
                placeholder="请输入名称"
                v-model.trim="condition.fileName"
                style="width:180px"
              />
              <a-select
                style="width: 350px"
                v-model="condition.companyCode"
                placeholder="请选择关联公司"
                :filter-option="filterOption"
                show-search
              >
                <a-select-option
                  :value="v.orgCode"
                  v-for="(v, i) in companySoucre"
                  :key="i"
                >
                  {{ v.orgName }}
                </a-select-option>
              </a-select>
              <a-select
                style="width: 350px"
                v-model="condition.proCode"
                placeholder="请选择关联项目"
                :filter-option="filterOption"
                show-search
              >
                <a-select-option
                  :value="v.proCode"
                  v-for="(v, i) in projectSource"
                  :key="i"
                >
                  {{ v.proName }}
                </a-select-option>
              </a-select>
              <!-- <a-date-picker
                mode="year"
                format="YYYY"
                valueFormat="YYYY"
                v-model="condition.year"
                :open="condition.isopen"
                placeholder="选择年份"
                @panelChange="yearPanel"
                @openChange="yearOpen"
                class="year-picker"
              /> -->
            </div>
            <div class="button-warp">
              <a-button type="primary" icon="search" @click="handleSearch()">
                查询
              </a-button>
              <a-button icon="sync" @click="handleReset()">重置</a-button>
            </div>
          </div>
        </div>
        <div class="table-container">
          <!-- show-overflow
            show-header-overflow -->
          <vxe-table
            ref="xTable"
            height="99%"
            align="center"
            border="inner"
            :data="tableData"
            :column-config="{ resizable: true }"
            size="small"
            :loading="tableLoading"
          >
            <vxe-column type="seq" width="80" title="序号"></vxe-column>
            <vxe-column
              :title="item.title"
              :field="item.key"
              :min-width="item.width"
              v-for="(item, index) in columns"
              :key="index"
              :align="item.align"
            >
            </vxe-column>
            <vxe-column title="查看/下载" width="100">
              <template #default="{ row }">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon
                    type="eye"
                    class="preview-btn"
                    @click="previewFile(row)"
                  />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    class="download-btn"
                    @click="downloadFile(row)"
                  />
                </a-tooltip>
              </template>
            </vxe-column>
            <vxe-column field="operate" title="操作" fixed="right" width="100">
              <template #default="{ row }">
                <div class="text-button-group">
                  <a-tooltip placement="top">
                    <template slot="title">
                      查看
                    </template>
                    <a-icon type="file-search" @click="handleAdd(row, 3)" />
                  </a-tooltip>
                  <!-- 编辑 -->
                  <a-tooltip placement="top" v-action:kjcggl_edit>
                    <template slot="title">
                      编辑
                    </template>
                    <a-icon
                      type="edit"
                      class="edit-btn"
                      @click="handleAdd(row, 2)"
                    />
                  </a-tooltip>
                  <!-- 删除 -->
                  <a-tooltip placement="top" v-action:kjcggl_delete>
                    <template slot="title">
                      删除
                    </template>
                    <a-icon
                      type="delete"
                      class="delete-btn"
                      @click="handleDelClick(row)"
                    />
                  </a-tooltip>
                </div>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <!-- 分页 -->
        <div class="pager-container">
          <vxe-pager
            size="small"
            background
            :current-page.sync="pager.page"
            :page-size.sync="pager.pageSize"
            :total="pager.total"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
            :page-sizes="[20, 50, 100, 500]"
            @page-change="paginationChange"
          >
            <template #left>
              <div class="vxe-pager-left-tip-container">
                共<span>{{ pager.total }}</span
                >条
              </div>
            </template>
          </vxe-pager>
        </div>
      </div>
    </div>

    <!-- 新增 -->
    <addModal
      :visible.sync="addModal.visible"
      :operateType="addModal.operateType"
      :parameter="addModal.row"
      :code="currentTreeNode.code"
    ></addModal>

    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>

    <!-- 附件列表 -->
    <filePreview
      :visible.sync="filePreview.visible"
      :fileList="filePreview.fileList"
    >
    </filePreview>
  </div>
</template>

<script>
// 科技成果管理
import moment from "moment";
import cloneDeep from "lodash.clonedeep";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import { mapGetters } from "vuex";
import { getToken, downloadDfs } from "@/utils/TopVUI";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
//新增
import addModal from "./components/addModal.vue";
//附件
import previewModal from "@/pages/document/minio/previewModal";
//附件列表
import filePreview from "@/components/extendCustom/file-preview";

import tableMixin from "./table.js";
import { getAllProListByQX } from "@/api/common.js";
import {
  getAchievementTree,
  getAchievementPage,
  deleteAchievement,
} from "@/api/knowledgeBase";
export default {
  mixins: [tableMixin],
  components: {
    IconFont,
    previewModal,
    addModal,
    filePreview,
  },
  data() {
    return {
      //查询体条件
      condition: {
        //公司名称
        companyCode: undefined,
        //项目名称
        proCode: undefined,
        //文件名称
        fileName: "",
        //类别
        type: undefined,
        //日期范围
        year: null,
        isopen: false,
      },
      //科技成果管理
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      cloneTreeData: [],
      currentTreeNode: {},
      keyWord: "",
      //table
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //附件列表
      filePreview: {
        visible: false,
        fileList: [],
      },
      //项目
      projectSource: [],
      //公司
      companySoucre: [],
      spinning: false,
      //
      isRefresh: false,
      //新增
      addModal: {
        visible: false,
        operateType: "1",
        row: {},
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },

  mounted() {
    Promise.all([
      this.getProjectData(),
      this.getCompanyData(),
      this.getTreeData(),
    ]);
  },
  methods: {
    handleAAA() {
      let { proCode } = this.conditionsData;
      this.$post(
        `/probusiness/archiveDirectory/createDirectory?proCode=${proCode}&type=8`,
        {},
        {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
          },
        }
      )
        .then((res) => {
          this.getTreeData();
        })
        .catch((_) => {});
    },

    //预览
    previewFile(row) {
      let { files = "[]", secondFiles = "[]" } = row;
      let files_1 = this.analysisPath(files);
      let files_2 = this.analysisPath(secondFiles);
      let list = [...files_1, ...files_2];
      if (list.length > 1) {
        this.filePreview.fileList = list;
        this.filePreview.visible = true;
        return;
      }
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { files = "[]", secondFiles = "[]" } = row;
      let files_1 = this.analysisPath(files);
      let files_2 = this.analysisPath(secondFiles);
      let list = [...files_1, ...files_2];
      if (list.length > 1) {
        this.filePreview.fileList = list;
        this.filePreview.visible = true;
        return;
      }
      let { url } = list?.[0] ?? {};
      if (!url) {
        this.$message.warning("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },

    analysisPath(files = "[]") {
      let list = JSON.parse(files ?? "[]");
      return list;
    },

    //新增
    handleAdd(item, type) {
      this.addModal.row = item;
      this.addModal.operateType = type;
      this.addModal.visible = true;
      this.isRefresh = true;
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteAchievement({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.isRefresh = true;
                that.getTreeData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //监听树形选择
    onSelect(selectedKeys, info) {
      let { code } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [code];
      this.pager.page = 1;
      this.getTableData();
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //查询项目
    getProjectData() {
      return new Promise((resolve, reject) => {
        getAllProListByQX({})
          .then((res) => {
            let { data } = res;
            this.projectSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.projectSource = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询公司
    getCompanyData() {
      return new Promise((resolve, reject) => {
        this.$get("/mdata/organization/getCompanyList", {})
          .then((res) => {
            let { data } = res;
            this.companySoucre = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.companySoucre = [];
            reject();
          });
      });
    },

    //查询项目列表-树形
    getTreeData() {
      this.spinning = true;
      let { proCode = "" } = this.condition;
      return new Promise((resolve, reject) => {
        getAchievementTree({ proCode: proCode })
          .then((res) => {
            let { data } = res;
            this.cloneTreeData = cloneDeep(data ?? []);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              this.cloneTreeData,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.tableData = [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.cloneTreeData = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.spinning = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      //
      if (!this.isRefresh) {
        let flatData = flatTreeData(treeData, "childList");
        let item = flatData.find(
          (v) => !v.childList || v.childList.length == 0
        );
        this.expandedKeys = flatData.map((v) => v.code).filter((v) => v);
        this.selectedKeys = [item.code];
        this.currentTreeNode = item;
      }
      //
      this.getTableData();
    },

    //查询分页数据
    getTableData() {
      this.initTableColumns();
      this.tableLoading = true;
      let { page, pageSize } = this.pager;
      let { code } = this.currentTreeNode;
      let { companyCode = "", proCode = "", fileName } = this.condition;
      getAchievementPage({
        page,
        pageSize,
        type: code,
        companyCode,
        proCode,
        fileName,
      })
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.tableLoading = false;
          this.isRefresh = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    handleSearch() {
      this.pager.page = 1;
      this.isRefresh = true;
      this.getTreeData();
    },
    handleReset() {
      this.condition.companyCode = undefined;
      this.condition.proCode = undefined;
      this.condition.fileName = "";
      this.handleSearch();
    },
    //选择年份
    yearPanel(e) {
      this.condition.year = moment(e).format("YYYY");
      this.condition.isopen = false;
    },
    yearOpen(status) {
      if (status) {
        this.condition.isopen = true;
      } else {
        this.condition.isopen = false;
      }
    },
    //查询图纸管理树
    handleFilterTree() {
      let { keyWord, cloneTreeData } = this;
      let cloneData = cloneDeep(cloneTreeData);
      this.treeData = this.filterTree(cloneData, "childList", (node) =>
        node.name.includes(keyWord)
      );
    },
    //过滤树形数据
    filterTree(data, children = "children", filterFunc) {
      return data
        .filter((node) => {
          // 如果当前节点符合条件，直接返回true
          if (filterFunc(node)) {
            return true;
          }
          // 如果当前节点有子节点，递归过滤子节点
          if (node[children]) {
            node[children] = this.filterTree(
              node[children],
              children,
              filterFunc
            );
            // 如果过滤后的子节点不为空，说明当前节点需要保留
            return node[children].length > 0;
          }
          // 当前节点不符合条件，也没有子节点或子节点不符合条件，返回false
          return false;
        })
        .map((node) => {
          // 创建新对象，避免修改原始数据
          return {
            ...node,
            [children]: node[children]
              ? this.filterTree(node[children], children, filterFunc)
              : [],
          };
        });
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    moment,
  },
};
</script>

<style lang="less" scoped>
.custom-knowledgeBase-container {
  position: relative;
  .drawing-container {
    width: 300px;
    .condition {
      input {
        width: 368px;
      }
    }
    .tree-container {
      overflow: hidden;
      .custom-tree-title-warp {
        .title {
          display: flex;
          justify-content: space-between;
          .num {
            font-family: Microsoft YaHei, Microsoft YaHei;
            font-weight: 400;
            font-size: 14px;
            color: #1890ff;
          }
        }
      }
    }
  }
  .right-container {
    .table-container {
      .text-button-group {
        /deep/.anticon-file-search {
          font-size: 15px;
        }
      }
    }
  }
}
</style>
